package com.by.basicweb.validator;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.List;

import static com.by.toolkit.utils.ExceptionUtil.getStackTrace;

@Slf4j
public class AllEmptyValidator implements ConstraintValidator<AllEmpty, Object> {


    private List<String> needValidFieldNameList;

    @Override
    public void initialize(AllEmpty constraintAnnotation) {
        needValidFieldNameList = Lists.newArrayList(constraintAnnotation.needValidFieldNameList());
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        try {
            if (CollectionUtil.isEmpty(needValidFieldNameList)) {
                return true;
            }
            for (String fieldName : needValidFieldNameList) {
                Field startDateField = value.getClass().getDeclaredField(fieldName);
                startDateField.setAccessible(true);
                if (ObjectUtil.isNotEmpty(startDateField.get(value))) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            log.info("[AllEmptyValidator][isValid] exception:{}", getStackTrace(e));
            return false;
        }
    }

}
